<template>
  <!-- 被保人清单 -->
  <div class="flex items-center justify-between mt-[30px]" style="font-size: 16px">
    <div class="flex items-center">
      <div class="w-[4px] h-[12px] bg-[#EF6800]"></div>
      <div class="ml-[10px] text-[#EF6800] font-bold">被保人清单</div>
    </div>
  </div>
  <div
    class="w-full flex items-center justify-between mt-[30px]"
    style="font-size: 14px"
    v-if="!disabled"
  >
    <div
      @click="batchDel"
      class="w-[86px] h-[30px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer rounded-[5px]"
    >
      批量删除
    </div>
    <div class="flex">
      <div
        @click="download"
        class="w-[86px] h-[30px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer mr-[30px] rounded-[5px]"
      >
        下载模板
      </div>

      <el-upload
        action="/seller/upload/uploadUser"
        drag
        :show-file-list="false"
        :on-success="onSuccess"
        :on-error="onError"
      >
        <template #default>
          <div
            class="w-[86px] h-[30px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer mr-[30px] rounded-[5px]"
          >
            模板导入
          </div>
        </template>
      </el-upload>

      <div
        @click="openDia"
        class="w-[86px] h-[30px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer rounded-[5px]"
      >
        批量快录
      </div>
    </div>
    <div
      @click="addUser"
      class="w-[86px] h-[30px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer rounded-[5px]"
    >
      新增成员
    </div>
  </div>
  <div>
    <!-- 表头头 -->
    <div
      class="flex items-center justify-between h-[38px] bg-[#FBFBFB] mt-[20px] pl-[20px]"
      style="font-size: 16px"
    >
      <div @click="clickCheckall()" class="cursor-pointer" v-if="!disabled">
        <el-image
          v-if="checked"
          :src="getAssetsFile('home/active.png')"
          class="w-[18px] h-[18px]"
        ></el-image>
        <el-image
          v-else
          :src="getAssetsFile('home/noactive.png')"
          class="w-[18px] h-[18px]"
        ></el-image>
      </div>
      <div class="h-[38px] flex justify-center items-center ml-[20px] w-[50px]">
        <span>序号</span>
      </div>
      <div class="w-[258px] h-[38px] flex justify-center items-center">
        <span class="text-[#F00505]">*</span>
        <span>姓名</span>
      </div>
      <div class="w-[258px] h-[38px] flex justify-center items-center">
        <span class="text-[#F00505]">*</span>
        <span>证件类型</span>
      </div>
      <div class="w-[258px] h-[38px] flex justify-center items-center">
        <span class="text-[#F00505]">*</span>
        <span>证件号码</span>
      </div>
      <div class="w-[258px] h-[38px] flex justify-center items-center">
        <span class="text-[#F00505]">*</span>
        <span>性别</span>
      </div>
      <div class="w-[258px] h-[38px] flex justify-center items-center">
        <span class="text-[#F00505]">*</span>
        <span>操作</span>
      </div>
    </div>
    <!-- 表格内容 -->
    <div>
      <div
        class="flex items-center justify-between h-[38px] mt-[20px] pl-[20px]"
        v-for="(item, index) in list"
      >
        <div @click="clickCheck(index)" class="cursor-pointer" v-if="!disabled">
          <el-image
            v-if="item.isActive"
            :src="getAssetsFile('home/active.png')"
            class="w-[18px] h-[18px]"
          ></el-image>
          <el-image
            v-else
            :src="getAssetsFile('home/noactive.png')"
            class="w-[18px] h-[18px]"
          ></el-image>
        </div>
        <div class="h-[38px] flex justify-center items-center ml-[20px] w-[50px]">
          <span style="font-size: 18px">{{ index + 1 }}</span>
        </div>
        <div class="w-[258px] h-[38px] flex justify-center items-center ml-[5px]">
          <el-input v-model="item.name" style="width: 216px" :disabled="disabled" />
        </div>
        <div class="w-[258px] h-[38px] flex justify-center items-center">
          <el-select
            v-model="item.card_type"
            class="m-2"
            placeholder="请选择"
            :disabled="disabled"
          >
            <el-option
              v-for="item in selectArr"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="w-[258px] h-[38px] flex justify-center items-center">
          <el-input v-model="item.id_card" style="width: 216px" :disabled="disabled" />
        </div>
        <div class="w-[258px] h-[38px] flex justify-center items-center ml-[5px]">
          <el-select
            v-model="item.sex"
            class="m-2"
            placeholder="请选择"
            :disabled="disabled"
          >
            <el-option
              v-for="item in selectSexArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="w-[258px] h-[38px] flex justify-center items-center">
          <div
            v-if="!disabled"
            @click="del(index)"
            class="w-[82px] h-[34px] flex justify-center items-center border-[#EF6800] text-[#EF6800] border rounded-[5px] cursor-pointer"
          >
            删除
          </div>
        </div>
      </div>
    </div>
  </div>
  <div>
    <el-dialog
      v-model="dialogTableVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="bg-[#F5F5F5] w-full h-[60px] relative">
        <div
          class="font-bold w-full flex justify-center items-center h-[60px]"
          style="font-size: 24px"
        >
          智能录入
        </div>
        <div
          @click="dialogTableVisible = false"
          class="w-[14px] h-[14px] absolute top-[20px] right-[30px] cursor-pointer"
        >
          <el-image
            :src="getAssetsFile('home/close.png')"
            class="w-full h-full"
          ></el-image>
        </div>
      </div>
      <div class="p-[20px]">
        <div class="text-red-500 mb-[20px]">
          每行一个名单，每行里的信息用空格或逗号分隔，示例：
        </div>
        <div class="mb-[20px]">赵六  310101199001011234</div>
        <div class="mb-[20px]">赵六 身份证  310101199001011234</div>
        <el-input v-model="textarea" :rows="10" type="textarea" />
      </div>
      <div class="flex justify-center pb-[20px] relative">
        <div
          @click="dialogTableVisible = false"
          class="w-[110px] h-[40px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer rounded-[5px]"
        >
          关闭
        </div>
        <div
          @click="sumbit"
          class="w-[110px] h-[40px] flex justify-center items-center bg-[#EF6800] text-white cursor-pointer rounded-[5px] ml-[30px]"
        >
          智能名单分析
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import getAssetsFile from "@/utils/getImageurl.ts";
import OSS from "ali-oss";
import { ref, inject, defineExpose, defineProps, watchEffect } from "vue";
import { uploadUser } from "@/utils/api";
const props = defineProps({
  user: { type: Array },
  userCardType: { type: Array }, //证件类型
  disabled: { type: Boolean, default: false },
});

const checked = ref(false);
const dialogTableVisible = ref(false);
const textarea = ref("");
const list = ref([] as any);
const global = inject<any>("global");
const message = inject<any>("message");
const selectVal = ref("身份证");
const selectArr = ref([] as any[]);
const selectSexArr = [
  {
    value: "男",
    label: "男",
  },
  {
    value: "女",
    label: "女",
  },
];
const file = ref("");
const selectTableArr = ref([] as any[]);
const sumbit = () => {
  let arr = textarea.value.split(/[(\r\n)\r\n]+/);
  arr.forEach((item, index) => {
    if (item == "" || item == "身份证") {
      arr.splice(index, 1);
    }
  });
  // console.log(arr);

  arr.forEach((_, i) => {
    let a = arr[i].split(/[(\s)\s]+/);

    let param = IdCard(a);

    list.value.push(param);
  });
  dialogTableVisible.value = false;
};
//识别性别
const IdCard = (arr: Array<string>) => {
  let index = 1; //判断字段中有没有身份证三个字 没有是1 有是2

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == "身份证") {
      index = 2;
    }
  }

  let sex = "";

  if (parseInt(arr[index].slice(-2, -1)) % 2 == 1) {
    sex = "男";
  } else {
    sex = "女";
  }

  let param = {
    name: arr[0],
    id_card: arr[index],
    sex: sex,
    card_type: "身份证",
  };
  return param;
};
//表头的选择
const clickCheckall = () => {
  checked.value = !checked.value;
  if (checked.value) {
    list.value.forEach((item: any, index: number) => {
      item.isActive = true;
      selectTableArr.value.push(index);
    });
  } else {
    list.value.forEach((item: any) => {
      item.isActive = false;
      selectTableArr.value = [];
    });
  }
};
//表格的选择
const clickCheck = (index: number) => {
  list.value[index].isActive = !list.value[index].isActive;
  if (list.value[index].isActive == true) {
    selectTableArr.value.push(index);
  }
};
//单个删除
const del = (i: number) => {
  list.value.splice(i, 1);
};
//批量删除
const batchDel = () => {
  let arr = [] as any[];
  list.value.forEach((item: any, index: number) => {
    if (selectTableArr.value.indexOf(index) >= 0) {
    } else {
      arr.push(item);
    }
  });
  list.value = arr;
  selectTableArr.value = [];
  //   indexArr.forEach((item: any) => {
  //     console.log(item);
  //    list.value = list.value.filter(
  //       (_: any, i: number) => i !== item
  //     );
  //     console.log(list.value);
  //   });
};
//新增成员
const addUser = () => {
  let param = {
    name: "",
    id_card: "",
    sex: "",
  };
  list.value.push(param);
};
//下载模板
const download = () => {
  window.open("/static/人员名单导入模板.xlsx");
};
//上传成功的回调
const onSuccess = (v: any) => {
  list.value = v.msg;
  // console.log(v.msg);
};
//上传失败的回调
const onError = (_: any) => {
  message.warning("上传失败");
  // console.log(v);
};
//上传照片
const httpRequest = (v: any) => {
  //index 0是营业执照，1是身份证正面 2是反面
  // console.log(v.file);

  // console.log(v);
  let e = v.file;
  var arr = e["name"].split(".");
  var img_type = arr[1];
  let client = new OSS({
    region: global.region,
    //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
    accessKeyId: global.accessKeyId,
    accessKeySecret: global.accessKeySecret,
    bucket: global.bucket,
  });
  //获取当前时间
  var date = new Date();
  var file_name =
    date.getFullYear() +
    "/" +
    (date.getMonth() + 1) +
    "/" +
    date.getDate() +
    "/" +
    date.getHours() +
    "_" +
    date.getMinutes() +
    "_" +
    date.getSeconds() +
    "_" +
    date.getMilliseconds();
  let filename = file_name + "." + img_type;

  let res_file = e;
  let progre = "";
  async function put() {
    try {
      //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
      let result = await client
        .multipartUpload(filename, res_file, {
          progress: () => {
            // console.log("上传进度：" + progre);
            //console.log(percentage); // 上传文件进度
          },
        })
        .then(async (item: any) => {
          message.success("上传成功");
          // console.log(item);
          file.value = global.oss_url + item.name;
          const res = await uploadUser({ file: file.value });
          // console.log(res);

          //that.$emit("change", res.name);
        })
        .catch((_: any) => {
          message.warning("图片上传失败");
          //return that.toast(0, "上传失败");
        });
    } catch (e) {
      message.warning("图片上传失败");
    }
  }

  put();
};
//批量录入
const openDia = () => {
  dialogTableVisible.value = true;
  textarea.value = "";
};
watchEffect(() => {
  if (props.user) {
    list.value = props.user;
  }
  if (props.userCardType) {
    selectArr.value = props.userCardType;
  }
});
defineExpose({
  list,
});
</script>

<style scoped lang="scss">
:deep(.el-upload-dragger) {
  padding: 0 !important;
  border: none !important;
}
</style>
